#include "charsetconverter.h"
#include <stdio.h>

charsetconverter::charsetconverter(const char *tocode, const char *fromcode):m_desc(NULL)
{
	const iconv_t cd = iconv_open(tocode, fromcode);
	if (cd != reinterpret_cast <iconv_t>(-1))
	{
		iconv_t *p = new iconv_t;
		*p = cd;

		m_desc = p;
	}
}

charsetconverter::charsetconverter(const string &tocode, const string &fromcode)
{
	const iconv_t cd = iconv_open(tocode.c_str(), fromcode.c_str());
	if (cd != reinterpret_cast <iconv_t>(-1))
	{
		iconv_t *p = new iconv_t;
		*p = cd;

		m_desc = p;
	}
}

charsetconverter::~charsetconverter()
{
	if (m_desc)
	{
		iconv_close(*static_cast <iconv_t*>(m_desc));
		delete static_cast <iconv_t *>(m_desc);
		m_desc = NULL;
	}
}

void charsetconverter::convert(char *inbuffer, size_t &inlen, char *outbuffer, size_t &outlen)
{
	if (m_desc == NULL)
	{
		return ;
	}

	const iconv_t cd = *static_cast <iconv_t*>(m_desc);

	char *inptr = inbuffer;
	char *outptr = outbuffer;

	if (iconv(cd, &inptr, &inlen, &outptr, &outlen) == static_cast<size_t>(-1))
	{
		perror("iconv");
		return ;
	}

	return ;
}
